package listener;

import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionListener;

@WebListener
public class OnlineListener implements HttpSessionListener {
    private static int online_count = 0;

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        ++online_count;
        HttpSession session = httpSessionEvent.getSession();
        session.getServletContext().setAttribute("online_count", online_count);
        System.out.println("A user is online!");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        --online_count;
        HttpSession session = httpSessionEvent.getSession();
        session.getServletContext().setAttribute("online_count", online_count);
    }
}
